package com.whz.crypt;

import java.io.*;
import java.nio.charset.StandardCharsets;

class FilePassword implements Password {

    private String filePathName;

    protected String fileContent;

    FilePassword(String pathName) throws IOException {
        filePathName = pathName;
        fileContent = readFile(pathName);
    }

    FilePassword(InputStream is) throws IOException {
        fileContent = read(is);
    }

    public static String read(InputStream is) throws IOException {
        int len;
        char[] b = new char[100];
        StringBuilder c = new StringBuilder();
        Reader in = new InputStreamReader(is, StandardCharsets.UTF_8);
        try {
            while ((len = in.read(b)) != -1) {
                c.append(b, 0, len);
            }
        } finally {
            in.close();
        }
        return c.toString();
    }

    public static String readFile(String fileName) throws IOException {
        FileInputStream stream = new FileInputStream(fileName);
        return read(stream);
    }

    public String getFilePathName() {
        return filePathName;
    }

    @Override
    public String getPassword() {
        return fileContent;
    }

    @Override
    public boolean checkValidate() {
        return true;
    }

}